class CheckoutController < ApplicationController  
  before_filter :initialize_cart
  
  protect_from_forgery :only => [:create, :update, :destroy] 

  def index
    @order = Order.new
    @page_title = "Checkout - Step 1"
    if @cart.artwork.empty?
      flash[:notice] = "Your shopping cart is empty"
      redirect_to :controller => 'catalogue'
    end
  end
  
  def place_order
    @page_title = "Checkout - Step 2"
    @order = Order.new(params[:order])   

    populate_order @order
    @order.status = "open"
    @order.last_edited_by = 0
    
    success = @order.save
    puts "result was:" + success.to_s
    
    if !success
        @order.error_message
        render :action => "index"
    end
  end
  
  def thank_you
    @cart.cart_items.destroy_all
    @page_title = "Thanks!"
  end
  
  private
  
  def populate_order o
    for cart_item in @cart.cart_items
      order_item = OrderItem.new(
        :artwork_id => cart_item.artwork_id,
        :price => cart_item.price,
        :amount => cart_item.amount)
      order_item.save!
      o.order_items << order_item
    end
  end
  
end
